package com.m3958.firstgwt.server.servlet;

import java.io.IOException;
import java.io.Writer;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.m3958.firstgwt.server.service.AppUtilService;
import com.m3958.firstgwt.server.service.WebContextFMCfg;

import freemarker.template.Template;
import freemarker.template.TemplateException;

@Singleton
public class ImgPreFetchServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	private Injector injector;
	
	@Inject
	private WebContextFMCfg fmCfg;
	
	@Inject
	private AppUtilService autils;
	
	@Inject
	protected com.google.inject.Provider<EntityManager> emp;

	/*
	 * 这个servlet返回的肯定是http方式的html
	 * 
	 */
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.setContentType("text/html;charset=UTF-8");   
		res.setCharacterEncoding("UTF-8");
		try {
			Template template = fmCfg.getTemplate("m3958-module-html/perfetch-iframe-source.html");
			Writer writer = res.getWriter();
			Map<String, Object> ro = new HashMap<String, Object>();
			Enumeration<String> pns = req.getParameterNames();
			Map<String, String> paras = new HashMap<String, String>();
			while(pns.hasMoreElements()){
				String pn = pns.nextElement();
				if("_imgs".equals(pn)){
					String imgs = req.getParameter("_imgs");
					if(imgs != null && !imgs.isEmpty()){
						String[] ss = imgs.split(",");
						ro.put("imgs", ss);
					}
				}
				paras.put(pn, req.getParameter(pn));					
			}
			String paramsJson = JSONObject.fromObject(paras).toString();
			ro.put("params", paramsJson);
			template.process(ro, writer);
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}
}
